package mysql_sync

import (
	"gc-rds-ha/internal/common"
	"gc-rds-ha/internal/dao/mysql_sync"
	"gc-rds-ha/internal/dao/sentinel"
	grpcError "gc-rds-ha/internal/error"
	sentinel2 "gc-rds-ha/internal/service/sentinel"
	msg "gc-rds-ha/scripts"
	"strings"

	log "github.com/sirupsen/logrus"

	"golang.org/x/net/context"
)

type RdsClusters interface {
	Discover(host string, port uint32) (*mysql_sync.DiscoverFormat, error)
	Forget(host string, port uint32) (*mysql_sync.DiscoverFormat, error)
	ClusterAliasInfo(clusterAlias string) ([]mysql_sync.TopologyInfo, error)
	Recover()
}

func GetSyncClusterType(s string) RdsClusters {
	var r RdsClusters
	t := common.AgentConfig.SyncType
	if s != "" {
		t = s
	}
	switch t {
	case "sentinel":
		r = &sentinel2.RdsClusterSentinel{}
	case "orch":
		r = &RdsClusterOrch{}
	default:
		r = &RdsClusterOrch{}
	}
	return r
}

func DoSyncECSClustersInfo(ctx context.Context, req *msg.STSyncECSClustersInfoReq) (*msg.STSyncECSClustersInfoRsp, error) {
	var (
		rsp *msg.STSyncECSClustersInfoRsp
	)
	log.WithFields(log.Fields{
		"req: ": req,
	}).Info("DoSyncECSClustersInfo request params")
	// orchestrator discover MasterIP

	discoverInfo, err := GetSyncClusterType("").Discover(req.MasterIp, req.MasterPort)
	if err != nil {
		log.WithFields(log.Fields{
			"req: ":          req,
			"discoverInfo: ": discoverInfo,
		}).Info("DoSyncECSClustersInfo.Discover error")
		return rsp, grpcError.GrpcErrArgsInvalid
	}
	mysqlProxyVip := &sentinel.MysqlProxyVip{
		MasterIP:        req.MasterIp,
		MasterPort:      req.MasterPort,
		ProxyIP:         strings.Join(req.ProxyIp, ","),
		IsDiscover:      1,
		NetWorkID:       req.Vip.NetworkId,
		SubNetID:        req.Vip.SubnetId,
		AzoneCode:       req.Vip.AzoneCode,
		RegionCode:      req.Vip.RegionCode,
		ResourceGroupID: req.Vip.ResourceGroupId,
		OwnerID:         req.Vip.OwnerId,
		OwnerType:       req.Vip.OwnerType,
	}

	// todo 绑定VIP到proxyIP，默认req.ProxyIp第一个
	mysqlProxyVip.VipBindProxyIP = ""
	defaultBindProxyIp := req.ProxyIp[0]
	if BindVipToProxy() {
		mysqlProxyVip.VipBindProxyIP = defaultBindProxyIp
	}

	// RDS-MYSQL集群和实例信息入库
	if err = mysqlProxyVip.Create(ctx); err != nil {
		return rsp, grpcError.GrpcErrDB
	}
	return rsp, nil
}
